/*
 * @lc app=leetcode.cn id=652 lang=typescript
 *
 * [652] 寻找重复的子树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

//  思路：树的序列化
//  由于树的序列化是唯一的，因此用来判断是否重复
//  利用map存储 树的序列化字符串 出现的次数
//  如果第一次重复出现则将节点加入解集

//  O(n2) O(n2)

function findDuplicateSubtrees(root: TreeNode | null): Array<TreeNode | null> {

    const map: Map<string, number> = new Map()
    const res: Array<TreeNode | null> = []

    //  序列化
    const serialization = (root: TreeNode | null): string => {

        if (!root) return '#'
        const left = serialization(root.left)
        const right = serialization(root.right)
        const seri = root.val + ',' + left + ',' + right

        map.set(seri, map.has(seri) ? map.get(seri) as number + 1
            : 1)

        if (map.get(seri) === 2) res.push(root)
        return seri
    }

    serialization(root)
    return res
};

// @lc code=end

import { TreeNode } from "./type"
const root = new TreeNode(1, new TreeNode(2, new TreeNode(4)), new TreeNode(3, new TreeNode(2, new TreeNode(4)), new TreeNode(4)))
const res = findDuplicateSubtrees(root)
res.forEach(item => {
    console.log(TreeNode.printTree(item))
})

